// pages/market/market.js

import { get } from 'mobx-miniprogram';
import { createStoreBindings } from 'mobx-miniprogram-bindings';
import { store } from '../../store/store';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    option1: [
      { text: '全部类型', value: 0 },
      { text: '快递类型', value: 1 },
    ],
    option2: [
      { text: '默认排序', value: 'a' },
      { text: '时间升序', value: 'b' },
      { text: '时间降序', value: 'c' },
      { text: '费用升序', value: 'd' },
      { text: '费用降序', value: 'e' },
    ],
    orders: [],
    value1: 0,
    value2: 'a',
    url: "/portal/orders/market",
    urlTakeOrder: "/portal/orders/rider/takeOrder",
    currentPage: 0,
  },

  getOrder(e) {
    console.log(e);
  },

  onClose(event) {
    const { position, instance } = event.detail;
    switch (position) {
      case 'left':
      case 'cell':
        instance.close();
        break;
      case 'right':
        Dialog.confirm({
          message: '确定删除吗？',
        }).then(() => {
          instance.close();
        });
        break;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 挂载全局数据
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['user'],
      actions: ['getUser', 'getWebsite']
    });

    this.setData({
      url: this.getWebsite() + this.data.url,
      urlTakeOrder: this.getWebsite() + this.data.urlTakeOrder,
    });

    this.getMarket();
  },

  getMarket() {
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });
    // 加载分页数据
    let that = this;
    let orders_new = this.data.orders;
    let page = this.data.currentPage + 1
    wx.request({
      url: this.data.url + "/" + page + "/" + this.data.value1 + "/" + this.data.value2,
      method: "GET",
      success (res) {  // 这种形式this会被修改，需要用that保存一下this，改成=>形式不用that了
        Toast.clear();
        if (res.data.data.length == 0) {
          Toast.clear(),
          Toast('没有更多数据了');
          return;
        }
        for (const key in res.data.data) {
            let date = that.formatDate(res.data.data[key].orderPostTime);
            res.data.data[key].orderPostTime = date;
            orders_new.push(res.data.data[key]);
          }
        that.setData({
          currentPage: that.data.currentPage + 1,
          orders: orders_new,
        })
      },
      fail (res) {
        console.log(res.data.msg);
      },
      complete () {
        setTimeout( () => {
          Toast.clear();
          wx.stopPullDownRefresh();
        }, 1000)
      }
    })
  },

  formatDate (time) {
    var date = new Date(time);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    var hour = function () { //获取小时
        return date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    }
    var minute = function () { //获取分钟
        return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    }

    var second = function () { //获取秒数
        return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    }
    return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ':' + second()
  },

  wantToAccept(res) {
    Dialog.confirm({
      message: '确认接受订单？',
    })
      .then(() => {
        // on confirm
        wx.request({
          url: this.data.urlTakeOrder,
          method: "POST",
          data: {
            orderId: res.currentTarget.dataset.id,
            riderId: this.data.user.id,
          },
          headers: {
            'Content-Type': 'application/json'  // 从请求体发送json对象
          },
          success: (result) => {
            Toast(result.data.msg);
            this.setData({
              currentPage: 0,
              orders: [],
            });
            this.getMarket();
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  onchange1(e) {
    this.setData({
      orders: [],
      currentPage: 0,
      value1: e.detail,
    });

    this.getMarket();
  },

  onchange2(e) {
    this.setData({
      orders: [],
      currentPage: 0,
      value2: e.detail,
    });

    this.getMarket();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 销毁挂载绑定
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      currentPage: 0,
      orders: [],
    })
    this.getMarket();
    Toast.clear();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getMarket();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})